package com.aneliya.validator.component;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.SwingUtilities;
import javax.swing.text.JTextComponent;

import com.aneliya.validator.Validator;
import com.aneliya.validator.data.EmptyStringValidator;

public class IdenticalTextComponentValidator extends Validator {
	protected JTextComponent component1;
	protected JTextComponent component2;
	
	public Boolean isValid() {
		return (component1.getText().equals(component2.getText()));
	}
	
	public Boolean isActive() {
		return (emptyStringValidator.isValid(component1.getText()) &&
				emptyStringValidator.isValid(component2.getText()));
	}
	
	private EmptyStringValidator emptyStringValidator;
	
	public IdenticalTextComponentValidator(
			JTextComponent component1, 
			JTextComponent component2) {
		super();
		this.component1 = component1;
		this.component2 = component2;
		
		emptyStringValidator = new EmptyStringValidator();
		initializeComponentsChangeListeners();
	}

	protected void initializeComponentsChangeListeners() {
		KeyListener listener = new KeyListener() {
			public void keyTyped(KeyEvent e) {
				SwingUtilities.invokeLater(new Runnable() {
					public void run() {
						dispatchValidatorChanged();
					}
				});
			}
			
			public void keyPressed(KeyEvent e) {
			}
			public void keyReleased(KeyEvent e) {
			}
		};
		component1.addKeyListener(listener);
		component2.addKeyListener(listener);
	}

}
